package com.yoomiito.app.ui.anyview.goodsinfo.header

import android.Manifest
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewStub
import android.widget.LinearLayout
import android.widget.TextView
import cn.droidlover.xdroidmvp.net.ApiException
import cn.droidlover.xdroidmvp.net.ApiSubscriber
import cn.droidlover.xdroidmvp.net.XApi
import com.umeng.socialize.bean.SHARE_MEDIA
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.isNull
import com.yoomiito.app.model.bean.GoodsDetail
import com.yoomiito.app.model.bean.ShareUrl
import com.yoomiito.app.model.bean.VideoInfo
import com.yoomiito.app.net.YmApi
import com.yoomiito.app.showToast
import com.yoomiito.app.strFilter
import com.yoomiito.app.ui.anyview.shareview.ShareView
import com.yoomiito.app.utils.*
import com.yoomiito.app.utils.video.MediaPlayerVideoInfo
import com.yoomiito.app.utils.video.MetadataRetrieverVideoInfo
import com.yoomiito.app.utils.video.VideoInfoUtil
import com.yoomiito.app.utils.wx.UMengShareUtils
import com.yoomiito.app.widget.dialog.ShareBottomDialog_1
import com.youth.banner.Banner
import com.youth.banner.BannerConfig
import com.youth.banner.Transformer
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

abstract class BaseGoodsInfoHeaderView(val context: BaseActivity<*>):LinearLayout(context){
    var OnVideoClickListener:(VideoInfo)->Unit={}
    private var goodsDetail:GoodsDetail?=null
    private lateinit var shareView:ShareView
    init {
        LayoutInflater.from(context).inflate(getLayoutId(), getParentView(), true)
    }

    fun initBanner(banner: Banner,goodsDetail : GoodsDetail){
//        val images = if (goodsDetail?.small_images == null
//                || goodsDetail?.small_images?.urls == null
//                || goodsDetail?.small_images!!.urls.size == 0
//        ) {
//            arrayListOf<String>()
//        } else {
//            goodsDetail?.small_images!!.urls
//        }
        this.goodsDetail = goodsDetail
        //设置banner样式
        banner.setBannerStyle(BannerConfig.NUM_INDICATOR)
        //设置图片加载器
        banner.setImageLoader(BannerImageLoader())
        //设置图片集合
        banner.setImages(goodsDetail.productImg.split(","))
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Default)
        //设置标题集合（当banner样式有显示title时）
//        banner.setBannerTitles(titles);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true)
        //设置轮播时间
        banner.setDelayTime(2500)
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER)
        //banner设置方法全部调用完毕时最后调用
        banner.start()
        banner.isFocusable = false
        banner.isFocusableInTouchMode = false
    }

    abstract fun getLayoutId():Int

    abstract fun getParentView():LinearLayout

    abstract fun initView(goodsDetail : GoodsDetail)

    fun getVideoTime(goodsDetail : GoodsDetail,result:(VideoInfo)->Unit){
        if (!TextUtils.isEmpty(goodsDetail.video)) {
            Observable.just<String>(goodsDetail.video)
                    .observeOn(Schedulers.io())
                    .map { s ->
                        var videoInfoUtil: VideoInfoUtil
                        try {
                            videoInfoUtil = MetadataRetrieverVideoInfo(s)//在vivo手机 系统6.1上会崩溃 这时候就使用MediaPlayerVideoInfo
                        } catch (e: Exception) {
                            videoInfoUtil = MediaPlayerVideoInfo(s)
                        }

                        val videoInfo = VideoInfo()
                        videoInfo.duration = videoInfoUtil.getVideoDuration()
                        videoInfo.width = videoInfoUtil.getVideoWidth()
                        videoInfo.height = videoInfoUtil.getVideoHeight()
                        videoInfo.url = s
                        videoInfoUtil.release()
                        videoInfo
                    }
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe { s ->
                        result(s)
                    }

        }
    }

    fun showShareDialog(){
        val shareDialog = ShareBottomDialog_1(context)
        shareDialog.setOnShareItemClickListener { i->
//            postShareNum()
            when(i){
                1->{
//                    val info = UmShareInfo()
//                    info.shareUrl = goodsDetail?.share_url
//                    info.title = goodsDetail?.title
//                    info.imgUrl = if(goodsDetail?.share_img?.isEmpty()!!)goodsDetail?.pict_url else goodsDetail?.share_img
//                    info.path = "/pages/index/mpcode?scene=${UserInfoConfig.getInviteCode()}_${goodsDetail?.num_iid}"
//                    info.id = "gh_fdaef843ac93"
//                    UMengShareUtils.shareWXMiniProgram(context,info)
                    UMengShareUtils.shareWX(context, goodsDetail?.recommended_language, goodsDetail?.share_url, goodsDetail?.title, goodsDetail?.share_img)
                }//微信好友
                2->{
                    UMengShareUtils.shareWXCircle(context, goodsDetail?.recommended_language, goodsDetail?.share_url, goodsDetail?.title, goodsDetail?.share_img)
                }
                3->share(i)//朋友圈
            }
            shareDialog.dismiss()
        }
        shareDialog.show()
        shareDialog.showSavePic(false)

    }
    fun updateGoodsInfo(goodsDetail : GoodsDetail){
        initView(goodsDetail)
    }

    fun goodsTitleCopy(titleTv:TextView,title:String){
        titleTv.setOnLongClickListener {
            AllUtils.copyText(context, title)
            "复制成功".showToast()
            false
        }
    }
    fun share(type:Int){
        AllUtils.requestPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE)
            .subscribe { aBoolean ->
                shareView = ShareView(context,goodsDetail!!)
                shareView.onPicMakeListener = {
                    when(type){
                        2->{
                            UMengShareUtils.shareWXPic(SHARE_MEDIA.WEIXIN_CIRCLE,context,it)
                        }//朋友圈
                        3->{
                            ImageLoader.getInstance().downloadPic(context,it)
                            "保存成功".showToast()
                        }//保存图片
                    }
                    context.dismissLoading()
                }
                getQRCodeUrl()
            }

    }
    private fun getQRCodeUrl(){
        context.showLoading()
        YmApi.getYmService()
            .getQRCodePic(goodsDetail?.num_iid.toString())
            .compose(context.bindToLifecycle())
            .compose(XApi.getApiTransformerData())
            .compose(XApi.getScheduler())
            .subscribe(object : ApiSubscriber<ShareUrl>(){
                override fun onSuccess(t: ShareUrl?) {
                    t?.url?.strFilter { !it.isNullOrEmpty() }?.let {
                        if (shareView.isNull()){
                            context.dismissLoading()
                        }else{
                            shareView.setQRCodeUrl(it)
                        }
                    }
                }

                override fun onFail(error: ApiException?) {
                    context.dismissLoading()
                    "图片生成失败，请稍候再试".showToast()
                }
            })
    }

    /**
     * true 未初始化
     * false 已初始化
     */
    fun viewStubIsInflate(resID:Int):Boolean = findViewById<View>(resID) is ViewStub

}